import React,{ useState, useEffect } from 'react';
import queryString from 'query-string';
import io from 'socket.io-client';
import { ENDPOINT } from '../../Config';
// 引入css文件
import './Chat.css';

// 消息组件
import InfoBar from '../InfoBar/InfoBar';
// 消息列表
import Messages from '../Messages/Messages';

// 发送消息组件
import Input from '../Input/Input';


let socket;

const Chat = ({ location }) => {
    // 返回一个 state，以及更新 state 的函数。name状态
    const [name, setName] = useState('');
    // 返回一个 state，以及更新 state 的函数。room状态
    const [room, setRoom] = useState('');
    // 设置当前消息
    const [message, setMessage] = useState('');
    // 设置当前消息
    const [messages, setMessages] = useState([]);

    /* 浏览器地址变更，就创建新的socket */
    useEffect(() => {
        const { name, room } = queryString.parse(location.search);
        socket = io(ENDPOINT);
        setName(name);
        setRoom(room);
        socket.emit('join', { name, room }, ({error}) => {
     
        });
    }, [ENDPOINT, location.search]);

    useEffect(() => {
        socket.on('message', (message) => {
            console.log('设置messages');
            setMessages([...messages, message])
        })
    }, [messages]);

    /* 发送消息列表 */
    const sendMessage = (event) => {
        // 阻止换行的默认行为
        event.preventDefault();
        if (message) {
            socket.emit('sendMessage',message, () => setMessage(''))
        }
    }
    console.log(message, messages);

    return (
        <div className="outerContainer">
            <div className="container">
                <InfoBar room={room} />
                <Messages messages={messages} name={name}/>
                <Input message={message} sendMessage={sendMessage} setMessage={setMessage} />
            </div>
        </div >
    )
}

export default Chat